package mv_igual_10;

import Ação.Escrita;
import Ação.Retirar;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;

public class Index extends javax.swing.JFrame
{
    //Declarando os objetos para deixar somente os números no CNPJ e armazenar os dados do TXT.
    Retirar pontoevirgula = new Retirar();
    Escrita escrever = new Escrita();
    public Index()
    {
        initComponents();
        this.setLocationRelativeTo(null);
        setTitle("Seja bem vindo!");
    }
    //Mascara do CNPJ.
    public static DefaultFormatterFactory setCNPJ()  
    {  
        MaskFormatter CNPJ = null;  
        try   
        {   
            CNPJ = new MaskFormatter("##.###.###/####-##");
            CNPJ.setValidCharacters("0123456789");
            CNPJ.setPlaceholderCharacter('_');
        }   
        catch (Exception pe) { }  
        DefaultFormatterFactory factory = new DefaultFormatterFactory(CNPJ, CNPJ);  
        return factory;  
    }
    
    @SuppressWarnings("unchecked")
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        JLNone = new javax.swing.JLabel();
        JLCNPJ = new javax.swing.JLabel();
        TxtEmpresa = new javax.swing.JTextField();
        BtAvancar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        TxtCNPJ = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bem vindo ao CJ");
        setBackground(java.awt.Color.white);
        setName("Index");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        JLNone.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        JLNone.setText("Empresa:");

        JLCNPJ.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        JLCNPJ.setText("CNPJ:");

        TxtEmpresa.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        TxtEmpresa.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        TxtEmpresa.setToolTipText("Digite o nome da Empresa.");

        BtAvancar.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        BtAvancar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Novo.png"))); // NOI18N
        BtAvancar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtAvancarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
        jLabel1.setText("Sistema Contábil Five!");

        TxtCNPJ.setFormatterFactory(setCNPJ());
        TxtCNPJ.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        TxtCNPJ.setToolTipText("Digite o CNPJ da Empresa.");
        TxtCNPJ.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(101, 101, 101)
                .addComponent(jLabel1))
            .addGroup(layout.createSequentialGroup()
                .addGap(170, 170, 170)
                .addComponent(JLNone))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(TxtEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, 388, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(182, 182, 182)
                .addComponent(JLCNPJ))
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(TxtCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, 359, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(155, 155, 155)
                .addComponent(BtAvancar, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(JLNone)
                .addGap(6, 6, 6)
                .addComponent(TxtEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(JLCNPJ)
                .addGap(4, 4, 4)
                .addComponent(TxtCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(BtAvancar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    //Verifica se existe a pasta, se não houver cria a pasta e após salva o arquivo e se houver só criar o arquivo.
    private void BtAvancarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtAvancarActionPerformed
        if ((pontoevirgula.Retirar(TxtCNPJ.getText()).equals("")) || (TxtEmpresa.getText().equals("")))
        {
            JOptionPane.showMessageDialog(null, "CNPJ e Nome da empresa são campos obrigatórios.");
        }
        else
        {
            try 
            {
                File pasta = new File ("C:/Temp/"+pontoevirgula.Retirar(TxtCNPJ.getText()));
                if (pasta.isDirectory())
                {   
                    SalvarTXT();
                    new Formulario().setVisible(true);
                }
                else
                {
                    pasta.mkdir();
                    SalvarTXT();
                    new Formulario().setVisible(true);
                }
            } 
            catch (IOException ex){}
        }
    }//GEN-LAST:event_BtAvancarActionPerformed
    //Confirmação da saída do sistema.
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        int sair = JOptionPane.showConfirmDialog(null, "Deseja relmente sair do sistema?", "Volte sempre!", JOptionPane.YES_NO_OPTION);
        if (sair == JOptionPane.YES_OPTION) 
        {
            System.exit(0);
        }
        else 
        {
            setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        }  
    }//GEN-LAST:event_formWindowClosing
    //Envia a pasta de destino e após salva os TextField no arquivo TXT, mas antes apaga o arquivo para não duplicar os dados.
    public void SalvarTXT()throws IOException
    {
        escrever.escrevendo(TxtEmpresa.getText(), pontoevirgula.Retirar(TxtCNPJ.getText()), "VEmpresa.txt");
        escrever.escrevendo(TxtCNPJ.getText(), pontoevirgula.Retirar(TxtCNPJ.getText()), "VCNPJ.txt");
    }
    public static void main(String args[]) 
    {
        try 
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) 
            {
                if ("Nimbus".equals(info.getName())) 
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } 
        catch (ClassNotFoundException ex) 
        {
            java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } 
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } 
        catch (IllegalAccessException ex) 
        {
            java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } 
        catch (javax.swing.UnsupportedLookAndFeelException ex) 
        {
            java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() 
        {
            public void run()
            {
                new Index().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BtAvancar;
    private javax.swing.JLabel JLCNPJ;
    private javax.swing.JLabel JLNone;
    private javax.swing.JFormattedTextField TxtCNPJ;
    private javax.swing.JTextField TxtEmpresa;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
}
